﻿/* $RCSFile: CrmContactTree.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmContactTree/CrmContactTree.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:47  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;


namespace AddonNice.PageModules.CrmContactTree
{
 	#region Local TraceSwitch 
	public class ContactTreeTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("ContactTreeTrace","Special Trace Switch for ExLookup");
	}
	#endregion Local TraceSwitch 

    public class AStr
    {

        public const string ShowContacts            =   "CRM_ACCOUNTTREE_SHOW_CONTACTS";
        public const string ShowIncidents           =   "CRM_ACCOUNTTREE_SHOW_INCIDENTS";
        public const string ShowRelations           =   "CRM_ACCOUNTTREE_SHOW_RELATIONS";
        public const string ShowQuotes              =   "CRM_ACCOUNTTREE_SHOW_QUOTES";
        public const string ShowOrders              =   "CRM_ACCOUNTTREE_SHOW_ORDERS";
        public const string ShowInvoices            =   "CRM_ACCOUNTTREE_SHOW_INVOICES";
        public const string ShowOpportunities       =   "CRM_ACCOUNTTREE_SHOW_OPPORTUNITIES";
        public const string ShowContracts           =   "CRM_ACCOUNTTREE_SHOW_CONTRACTS";
        public const string ShowInactive            =   "CRM_ACCOUNTTREE_SHOW_INACTIVE_STATUS";
        public const string AlwaysShowOpenInCrm     =   "CRM_ACCOUNTTREE_SHOW_ALWAYS_OPENINCRM";
        
    }

    /// <summary>
    /// Initializer class for CrmContactTree 
    /// </summary>
    public class CrmContactTreeSI : PortalCRMModuleControlSI
    {
        public CrmContactTreeSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmContactTreeSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmContactTreeSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmContactTreeSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            string extgrp                       =   pm.ExtendedResourcesGroup;

            SettingItemSpecial ShowContacts     =   new SettingItemSpecial(AStr.ShowContacts,new BooleanDataType());
            ShowContacts.Value                  =   StStr.strTrue;
            ShowContacts.Order                  =   10;
            ShowContacts.ExtendedGroupName      =   extgrp;
            ShowContacts.EnglishName            =   "Show contacts";
            ShowContacts.Description            =   "Display contacts for selected contact.";
            bSettings.AddSetting(ShowContacts);

            SettingItemSpecial ShowIncidents    =   new SettingItemSpecial(AStr.ShowIncidents,new BooleanDataType());
            ShowIncidents.Value                 =   StStr.strTrue;
            ShowIncidents.Order                 =   15;
            ShowIncidents.ExtendedGroupName     =   extgrp;
            ShowIncidents.EnglishName           =   "Show incidents";
            ShowIncidents.Description           =   "Display incidents for selected contact.";
            bSettings.AddSetting(ShowIncidents);

            SettingItemSpecial ShowRelations     =   new SettingItemSpecial(AStr.ShowRelations,new BooleanDataType());
            ShowRelations.Value                  =   StStr.strTrue;
            ShowRelations.Order                  =   20;
            ShowRelations.ExtendedGroupName      =   extgrp;
            ShowRelations.EnglishName            =   "Show relations";
            ShowRelations.Description            =   "Display relations for selected contact.";
            bSettings.AddSetting(ShowRelations);
            
            SettingItemSpecial ShowQuotes       =   new SettingItemSpecial(AStr.ShowQuotes,new BooleanDataType());
            ShowQuotes.Value                    =   StStr.strTrue;
            ShowQuotes.Order                    =   30;
            ShowQuotes.ExtendedGroupName        =   extgrp;
            ShowQuotes.EnglishName              =   "Show quotes";
            ShowQuotes.Description              =   "Display quotes for selected contact.";
            bSettings.AddSetting(ShowQuotes);

            SettingItemSpecial ShowOrders       =   new SettingItemSpecial(AStr.ShowOrders,new BooleanDataType());
            ShowOrders.Value                    =   StStr.strTrue;
            ShowOrders.Order                    =   40;
            ShowOrders.ExtendedGroupName        =   extgrp;
            ShowOrders.EnglishName              =   "Show orders";
            ShowOrders.Description              =   "Display orders for selected contact.";
            bSettings.AddSetting(ShowOrders);

            SettingItemSpecial ShowInvoices     =   new SettingItemSpecial(AStr.ShowInvoices,new BooleanDataType());
            ShowInvoices.Value                  =   StStr.strTrue;
            ShowInvoices.Order                  =   50;
            ShowInvoices.ExtendedGroupName      =   extgrp;
            ShowInvoices.EnglishName            =   "Show invoices";
            ShowInvoices.Description            =   "Display invoices for selected contact.";
            bSettings.AddSetting(ShowInvoices);

            SettingItemSpecial ShowOpportunities        =   new SettingItemSpecial(AStr.ShowOpportunities,new BooleanDataType());
            ShowOpportunities.Value                     =   StStr.strTrue;
            ShowOpportunities.Order                     =   60;
            ShowOpportunities.ExtendedGroupName         =   extgrp;
            ShowOpportunities.EnglishName               =   "Show opportunities";
            ShowOpportunities.Description               =   "Display opportunities for selected contact.";
            bSettings.AddSetting(ShowOpportunities);
            
            SettingItemSpecial ShowContracts            =   new SettingItemSpecial(AStr.ShowContracts,new BooleanDataType());
            ShowContracts.Value                         =   StStr.strTrue;
            ShowContracts.Order                         =   65;
            ShowContracts.ExtendedGroupName             =   extgrp;
            ShowContracts.EnglishName                   =   "Show contracts";
            ShowContracts.Description                   =   "Display contracts for selected contact.";
            bSettings.AddSetting(ShowContracts);

            SettingItemSpecial AlwaysShowOpenInCrm      =   new SettingItemSpecial(AStr.AlwaysShowOpenInCrm,new BooleanDataType());
            AlwaysShowOpenInCrm.Value                   =   StStr.strTrue;
            AlwaysShowOpenInCrm.Order                   =   70;
            AlwaysShowOpenInCrm.ExtendedGroupName       =   extgrp;
            AlwaysShowOpenInCrm.EnglishName             =   "Always show 'open in crm'link";
            AlwaysShowOpenInCrm.Description             =   "When using IE browser, always show a link to open related entities in Crm.";
            bSettings.AddSetting(AlwaysShowOpenInCrm);
            
            SettingItemSpecial ShowInactive             =   new SettingItemSpecial(AStr.ShowInactive,new BooleanDataType());
            ShowInactive.Value                          =   StStr.strFalse;
            ShowInactive.Order                          =   80;
            ShowInactive.ExtendedGroupName              =   extgrp;
            ShowInactive.EnglishName                    =   "Show inactive status";
            ShowInactive.Description                    =   "Show all objects with inactive status.";
            bSettings.AddSetting(ShowInactive);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmContactTreeSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    /// Use General Queries to fill ables, bin these tables to combos
    /// Cascading between Combos is obtained when a new item is selected.
    /// When selection by program, cascading is in real time
    /// When selection is made by user, a callback will fill next combos
    /// Update button will fill the lookup in the client frame with the selected value
    /// </summary>
    public partial class CrmContactTree : PortalCRMModuleControl
    {
        
        #region General implementation

		/// <summary>
		/// 3 or 4
		/// </summary>
		public override VersionType ModuleType
		{
			get
			{
				return VersionType.CrmV3|VersionType.CrmV4;
			}
		}

        public override Guid GuidID
        {
            get
            {
                return new Guid("{751E8F56-1A74-431b-9940-5BEE8C2B5A43}");
            }
        }
        #endregion General implementation

        #region properties

        const string strPageMenu    =   "contactMenu";

        string _CrmServerUrl    =   string.Empty;
        public  string CrmServerUrl
        {
            get
            {
                if ( _CrmServerUrl == string.Empty )
                {
                    string url      =   Wrapper.CrmServiceUrl.ToLowerInvariant();
                    int idx         =   url.IndexOf("mscrmservice");
                    _CrmServerUrl   =   string.Format("{0}{1}/",url.Substring(0,idx),Wrapper.OrganizationName);
                    if ( ContactTreeTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree CrmServerUrl GET : '{0}'.",_CrmServerUrl),ContactTreeTrace.Sw.Info);
                }

                return _CrmServerUrl;
            }
        }
        bool ShowInactiveStatus
        {
            get
            {
                return ( Settings[AStr.ShowInactive].ToBool());
            }
        }

        bool ShowOpenInCrmLink
        {
            get
            {
                if (Request.Browser.MSDomVersion.Major == 0) // Non IE Browser?)   
                    return false;
                return (IsUnderCRM || Settings[AStr.AlwaysShowOpenInCrm].ToBool());
            }
        }

        EntityConfig _TConfig2 = null;
        public EntityConfig TConfig2
        {
            get
            {
                if (_TConfig2 == null)
                {
                    _TConfig2       =   new EntityConfig(Wrapper,CrmStr.contact);
                    if ( ContactTreeTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree TConfig2 Ctor vflag: [{0}], DisplayMask: [{1}].",
                            _TConfig2.entityFlags, _TConfig2.DisplayMask),ContactTreeTrace.Sw.Info);
                }
                return _TConfig2;
            }
        }

        SortedList<Guid,ADNDynContact> NotFoundContacts =   new SortedList<Guid,ADNDynContact>();
        SortedList<Guid,ADNDynContact> NotFoundAccount  =   new SortedList<Guid,ADNDynContact>();

        #endregion properties

        public CrmContactTree()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree Ctor BEG.",ModuleTraceSwitch.Sw.Info);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree Ctor END.",ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "CRMCONTACTTREE";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmContactTreeSI(bSettings,this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ContactTreeTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree Page_Load BEG IsPostBack: {0}, IsUnderCRM: {1}.",IsPostBack,IsUnderCRM),
                    (ContactTreeTrace.Sw.TraceVerbose)? ContactTreeTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            AddAjaxSetting(GridDock,RadTree1);
            AddAjaxSetting(GridDock,RadTree2);
            AddAjaxSetting(RadTree1,RadTree1);
            AddAjaxSetting(RadTree1,RadTree2);
            RadGrid RadGrid2    =   (RadGrid)GridDock.ContentContainer.FindControl("RadGrid2");
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree Page_Load RadGrid2 null: {0}.", RadGrid2 == null ),ContactTreeTrace.Sw.Info);
            if (RadGrid2 != null)
            {
                AddAjaxSetting(RadTree1, RadGrid2);
            }
            if (!IsPostBack)
            {
                Guid StartId    =   Guid.Empty;
			    // After up or down button when the page is refreshed, 
			    // select the previously selected tab from the list.
                if ( IsUnderCRM && ( RequestEntityTypename == CrmStr.contact ) )
			    {
				    try
				    {
                        StartId     =   EntityID;
                        if (ContactTreeTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree Page_Load StartId: {0}",StartId),ContactTreeTrace.Sw.Info);
				    }
				    catch(Exception ex)
				    {
		                if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree Page_Load ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
				    }
			    }
                RadTreeNode parentNode  =   LoadContacts(StartId,null);
                if ((StartId != Guid.Empty) && parentNode != null)
                {
                    SelectNode(parentNode);
                    LoadSubContacts(parentNode);
                }
                // insert context menu
                RadTree1.ContextMenus.Add(CreateContextMenu1());

            }
        }
        
		/// <summary>
		/// Create the context menu for contact treeview
		/// </summary>
		RadTreeViewContextMenu CreateContextMenu1()
		{

			RadTreeViewContextMenu cm	=   new RadTreeViewContextMenu();
            cm.ID                       =   strPageMenu;

            RadMenuItem cmi			    =	new RadMenuItem();
			cmi.Value			        =	"CloseContact";
            cmi.ImageUrl                =   portalSettings.GetImageFromThemeSkins("DeleteBtn");
			cmi.Text			        =	LocalizeHelper.Localize("CRM_CONTACTREE_CLOSE","Close");
			cmi.PostBack		        =	true;
			cm.Items.Add(cmi);

			cmi					        =	new RadMenuItem();
			cmi.Value			        =	"AddContact";
            cmi.ImageUrl                =   portalSettings.GetImageFromThemeSkins("AddPage");
			cmi.Text			        =	LocalizeHelper.Localize("CRM_CONTACTREE_ADD_CONTACT","Add Contact");
			cmi.PostBack		        =	true;
			cm.Items.Add(cmi);

            return cm;
		}
		
        void LoadSubContacts(RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree LoadSubContacts BEG parentNode: {0}, Nodes.Count: {1}", parentNode.Text,parentNode.Nodes.Count),ContactTreeTrace.Sw.Info);
            foreach (RadTreeNode nd in parentNode.Nodes)
            {
                Guid nId            =   new Guid(nd.Value);
                RadTreeNode subnd   =   LoadContacts(nId,nd);
                LoadSubContacts(subnd);
            }
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree LoadSubContacts END parentNode: {0}", parentNode.Text),ContactTreeTrace.Sw.Info);
        }

        RadTreeNode LoadContacts(Guid StartId,RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree LoadContacts BEG StartID: {0}, parentNode null: {1}", StartId, (parentNode == null)),ContactTreeTrace.Sw.Info);
            InternalQueryExpression query                       =   new InternalQueryExpression();
            InternalFilterExpression filter                     =   new InternalFilterExpression();
            filter.FilterOperator                               =   InternalLogicalOperator.And;
            InternalConditionExpression cond                    =   new InternalConditionExpression();

            if ( StartId != Guid.Empty )
            {
                if (parentNode == null)
                {
                    ADNDynContact acc0                          =   new ADNDynContact(Wrapper,StartId);
                    acc0.Retrieve();
                    parentNode                                  =   new RadTreeNode (acc0.name, StartId.ToString());
                    RadTree1.Nodes.Add(parentNode);
                }
                cond.AttributeName                              =   CrmStr.parentcustomerid;
                cond.Operator                                   =   InternalConditionOperator.Like;
                cond.Values                                     =   new object[] { StartId };
                if ( ShowInactiveStatus )
                        filter.Conditions                       =   new InternalConditionExpression[] {cond};
                else    filter.Conditions                       =   new InternalConditionExpression[] {cond, CRMUtil.StateCodeIsActiveCondition};
            }
            else if ( !ShowInactiveStatus )
                    filter.Conditions                           =   new InternalConditionExpression[] {CRMUtil.StateCodeIsActiveCondition};


            query.Criteria                                      =   filter;
            query.EntityName                                    =   CrmStr.contact;
            query.ColumnSet                                     =   new InternalAllColumns();

            GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.contact);
            InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
            PropertyDescriptorCollection _columnDescriptors     =   null;
            int count                                           =   0;
            Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                delegate(InternalDynamicEntity de)
                {
                    ADNDynContact ob                            =   new ADNDynContact();
                    ob.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    ob.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   ob.PropertyDescriptorCollection;
                    if ( ContactTreeTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree LoadContacts adding contact.fullname: [{0}], count: {1}", ob.fullname,count),ContactTreeTrace.Sw.Info);
                    AddNode(ob);
                    count++;
                    return true; //continue
                });
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree LoadContacts END parentNode null: {0}", (parentNode == null )),ContactTreeTrace.Sw.Info);
            return parentNode;
        }

        void AddNode(ADNDynContact myContact)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree AddNode BEG myContact.fullname: {0}, parentcustomerid: {1}", myContact.fullname,myContact.parentcustomerid),ContactTreeTrace.Sw.Info);

            RadTreeNode newNode         =   null;
            Guid parentcustomerid       =   myContact.parentcustomerid;
            RadTreeNode parentNode      =   null;
            if (parentcustomerid == Guid.Empty || ( myContact.parentCustomerType == CrmStr.account) )
            {
                newNode                 =   new RadTreeNode (myContact.fullname, myContact.contactid.ToString());//, srv + "_imgs/ico_18_1.gif", string.Empty, string.Empty);
                newNode.Expanded        =   false;
                RadTree1.Nodes.Add(newNode);
                if ( ContactTreeTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree AddNode added newNode.Text: {0}", newNode.Text),ContactTreeTrace.Sw.Info);
                if ( parentcustomerid != Guid.Empty )
                    NotFoundAccount.Add(parentcustomerid,myContact);
            }
            else
            {
                parentNode              =   RadTree1.FindNodeByValue(parentcustomerid.ToString());
                if ( ContactTreeTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree AddNode parentNode found: {0}", (parentNode != null)),ContactTreeTrace.Sw.Info);
                if (parentNode == null)
                    NotFoundContacts.Add(myContact.contactid, myContact);
                else
                {
                    newNode             =   new RadTreeNode (myContact.fullname, myContact.contactid.ToString());//, srv + "_imgs/ico_18_1.gif", string.Empty, string.Empty);
                    newNode.Expanded    =   false;
                    parentNode.Nodes.Add(newNode);
                }
            }
            // try to see if any notfound contact is a child of this contact
            if ( newNode != null )
            {
                for (int i = 0; i < NotFoundContacts.Count; i++)
                {
                    ADNDynContact acc       =   NotFoundContacts.Values[i];
                    if (acc.parentcustomerid == myContact.contactid)
                    {
                        RadTreeNode nNode   =   new RadTreeNode(acc.fullname, acc.contactid.ToString());
                        nNode.Expanded      =   false;
                        newNode.Nodes.Add(nNode);
                        if ( ContactTreeTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree AddNode parentNode found removing nNode: {0}", nNode.Text),ContactTreeTrace.Sw.Info);
                        NotFoundContacts.RemoveAt(i);
                        i--;
                    }
                }
            }
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ContactTree AddNode END.",ContactTreeTrace.Sw.Info);
        }
 
		void RadTree1_NodeClick(object o, RadTreeNodeEventArgs e)
		{
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeClick Text:{0}, Selected: {1}", e.Node.Text,e.Node.Selected),ContactTreeTrace.Sw.Info);
	        SelectNode(e.Node);
        }

        /// <summary>
        /// Fills the RadGrid with information from selected node
        /// If no node, empties the grid
        /// </summary>
        protected void SelectNode(RadTreeNode selectedNode)
        {
            if ( selectedNode == null )
                return;
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree SelectNode Text:{0}, Selected: {1}", selectedNode.Text,selectedNode.Selected),ContactTreeTrace.Sw.Info);
            RadGrid RadGrid2    =   (RadGrid)GridDock.ContentContainer.FindControl("RadGrid2");
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree SelectNode RadGrid2 null: {0}.", RadGrid2 == null ),ContactTreeTrace.Sw.Info);
            if ( RadGrid2 == null )
                return;
            selectedNode.Selected           =   true;
            RadTree2.Nodes.Clear();
            FillDetail(selectedNode);
            Guid contactId                  =   new Guid(selectedNode.Value);
            ADNDynContact myContact         =   new ADNDynContact(Wrapper,contactId);
            myContact.Retrieve();


            DataTable InfoTb                =   new DataTable();
            const string colName            =   "Name";
            const string colParameter       =   "Parameter";

			InfoTb.Columns.Add(colName, typeof(string));
			InfoTb.Columns.Add(colParameter, typeof(string));
            try
            {
                DataRow rw                  =   InfoTb.NewRow();
                rw[colName]                 =   LocalizeHelper.Localize("AM_NAME", "Name");
                string ntext                =   selectedNode.Text;
                rw[colParameter]            =   ntext;
                InfoTb.Rows.Add(rw);

                if ( myContact.ContainsKey(CrmStr.jobtitle) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_JOBTITLE", "Job title");
                    rw[colParameter]            =   myContact.jobtitle;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.employeeid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_EMPLOYEEID", "Employee Id");
                    rw[colParameter]            =   myContact.employeeid;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.defaultpricelevelid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PRICELEVEL", "Default price level");
                    rw[colParameter]            =   myContact.defaultpricelevelName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.ownerid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OWNER", "Owner");
                    rw[colParameter]            =   myContact.ownerName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.telephone1) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PHONE", "Phone 1");
                    rw[colParameter]            =   myContact.telephone1;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.fax) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_FAX", "Fax");
                    rw[colParameter]            =   myContact.fax;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.emailaddress1) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_EMAIL", "Email");
                    rw[colParameter]            =   myContact.emailaddress1;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.parentcustomerid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTREE_PARENTCUSTOMER", "Parent customer");
                    ADNDynCustomer cust         =   myContact.RetrieveCustomer();
                    rw[colParameter]            =   cust.customerName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.accountrolecode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_ACCOUNTROLE", "Sic");
                    rw[colParameter]            =   myContact.accountrolecodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.address1_line1) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ADDRESS1", "Address");
                    rw[colParameter]            =   myContact.address1_line1;
                    InfoTb.Rows.Add(rw);
                }
                if ( !string.IsNullOrEmpty(myContact.address1_line2) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   string.Empty;
                    rw[colParameter]            =   myContact.address1_line2;
                    InfoTb.Rows.Add(rw);
                }
                if ( !string.IsNullOrEmpty(myContact.address1_line3) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   string.Empty;
                    rw[colParameter]            =   myContact.address1_line3;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.address1_city) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CITY", "City");
                    rw[colParameter]            =   myContact.address1_city;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.address1_postalcode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_POSTAL_CODE", "Postal code");
                    rw[colParameter]            =   myContact.address1_postalcode;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.address1_stateorprovince) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATEORPROVINCE", "State");
                    rw[colParameter]            =   myContact.address1_stateorprovince;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.address1_country) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_COUNTRY", "Country");
                    rw[colParameter]            =   myContact.address1_country;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.annualincome) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_ANNUALINCOME", "Annual income");
                    rw[colParameter]            =   string.Format("{0} {1}",myContact.annualincome,myContact.transactioncurrencyName);
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.salutation) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_SALUTATION", "Salutation");
                    rw[colParameter]            =   myContact.salutation;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.birthdate) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_BIRTHDATE", "Birth date");
                    rw[colParameter]            =   myContact.birthdate;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.assistantname) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_ASSISTANTNAME", "Assistant name");
                    rw[colParameter]            =   myContact.assistantname;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.assistantphone) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_ASSISTANTPHONE", "Assistant phone");
                    rw[colParameter]            =   myContact.assistantphone;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.creditlimit) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CREDITLIMIT", "Credit limit");
                    rw[colParameter]            =   string.Format("{0} {1}",myContact.creditlimit,myContact.transactioncurrencyName);
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.creditonhold) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACCOUNT_CREDITONHOLD", "Credit on hold");
                    rw[colParameter]            =   myContact.creditonhold.ToString();
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.paymenttermscode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PAYMENT_TERM", "Payment term");
                    rw[colParameter]            =   myContact.paymenttermscodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.educationcode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_EDUCATION", "Education level");
                    rw[colParameter]            =   myContact.educationcodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.externaluseridentifier) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_EXTERNALIDENTIFIER", "External user identifier");
                    rw[colParameter]            =   myContact.externaluseridentifier;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.familystatuscode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_FAMILYSTATUS", "Rating");
                    rw[colParameter]            =   myContact.familystatuscodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.gendercode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_GENDER", "Gender");
                    rw[colParameter]            =   myContact.gendercodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                
                if ( myContact.ContainsKey(CrmStr.suffix) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_SUFFIX", "Suffix");
                    rw[colParameter]            =   myContact.suffix;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.spousesname) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_SPOUSESNAME", "Spouses name");
                    rw[colParameter]            =   myContact.spousesname;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.customersizecode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACCOUNT_CUSTOMERSIZE", "Customer size");
                    rw[colParameter]            =   myContact.customersizecodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.customertypecode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACCOUNT_CUSTOMERTYPE", "Customer type");
                    rw[colParameter]            =   myContact.customertypecodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.governmentid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_GOVERNMENTID", "Industry code");
                    rw[colParameter]            =   myContact.governmentid;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.numberofchildren) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_NUMBERCHILDREN", "Number of children");
                    rw[colParameter]            =   myContact.numberofchildren.ToString();
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.haschildrencode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_HASCHILDREN", "Has children");
                    rw[colParameter]            =   myContact.haschildrencodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.isbackofficecustomer) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_ISBACKOFFICE", "Is backoffice customer");
                    rw[colParameter]            =   myContact.isbackofficecustomer.ToString();
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.preferredappointmentdaycode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PREFERED_APPOINTMENTDAY", "Prefered appointment day");
                    rw[colParameter]            =   myContact.preferredappointmentdaycodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                
                if ( myContact.ContainsKey(CrmStr.preferredappointmenttimecode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_PREFERED_APPOINTMENTTIME", "Prefered appointment time");
                    rw[colParameter]            =   myContact.preferredappointmenttimecodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.preferredcontactmethodcode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PREFERED_CONTACTMETHOD", "Prefered contact method");
                    rw[colParameter]            =   myContact.preferredcontactmethodcodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.shippingmethodcode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_SHIPPINGMETHOD", "Shipping method");
                    rw[colParameter]            =   myContact.shippingmethodcodeLabel;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.preferredequipmentid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PREFERED_EQUIPMENT", "Prefered equipment");
                    rw[colParameter]            =   myContact.preferredequipmentidName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.preferredserviceid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PREFERED_SERVICE", "Prefered service");
                    rw[colParameter]            =   myContact.preferredserviceidName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.preferredsystemuserid) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PREFERED_USER", "Prefered user");
                    rw[colParameter]            =   myContact.preferredsystemuseridName;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.websiteurl) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACCOUNT_WEBSITE", "Web site");
                    rw[colParameter]            =   myContact.websiteurl;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.ftpsiteurl) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_FTPSITE", "Ftp site");
                    rw[colParameter]            =   myContact.ftpsiteurl;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.nickname) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_NICKNAME", "Nickname");
                    rw[colParameter]            =   myContact.nickname;
                    InfoTb.Rows.Add(rw);
                }
                if ( myContact.ContainsKey(CrmStr.pager) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_CONTACTTREE_PAGER", "Pager");
                    rw[colParameter]            =   myContact.pager;
                    InfoTb.Rows.Add(rw);
                }            
                if ( myContact.ContainsKey(CrmStr.territorycode) )
                {
                    rw                          =   InfoTb.NewRow();
                    rw[colName]                 =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACCOUNT_TERRITORY", "Territory");
                    rw[colParameter]            =   myContact.territorycodeLabel;
                    InfoTb.Rows.Add(rw);
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree SelectNode Building ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
            }
            try
            {
                RadGrid2.DataSource = InfoTb;
                RadGrid2.DataBind();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree SelectNode Binding ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
        /// Load Detail TreeView
        /// </summary>
        protected void FillDetail(RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree FillDetail BEG parentNode: {0}, ID: {1}", parentNode.Text,parentNode.Value),ContactTreeTrace.Sw.Info);
            Guid contactId              =   new Guid(parentNode.Value);

            bool ShowContacts           =   Settings[AStr.ShowContacts].ToBool();
            bool ShowIncidents          =   Settings[AStr.ShowIncidents].ToBool();
            bool ShowRelations          =   Settings[AStr.ShowRelations].ToBool();
            bool ShowQuotes             =   Settings[AStr.ShowQuotes].ToBool();
            bool ShowOrders             =   Settings[AStr.ShowOrders].ToBool();
            bool ShowInvoices           =   Settings[AStr.ShowInvoices].ToBool();
            bool ShowOpportunities      =   Settings[AStr.ShowOpportunities].ToBool();
            bool ShowContracts          =   Settings[AStr.ShowContracts].ToBool();
            if ( ShowRelations )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_RELATIONS", "Relations");
                RadTreeNode nodeRelations   =   new RadTreeNode(str, CrmStr.relationshiprole);
                nodeRelations.Expanded      =   false;
                RadTree2.Nodes.Add(nodeRelations);
                loadRelations(contactId, nodeRelations);
            }
            if ( ShowContacts )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTACTS", "Contacts");
                RadTreeNode nodeContacts    =   new RadTreeNode(str, CrmStr.contact);
                RadTree2.Nodes.Add(nodeContacts);
                nodeContacts.Expanded       =   false;
                loadContacts(contactId, nodeContacts);
            }
            if ( ShowOpportunities )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPPORTUNITIES", "Opportunities");
                RadTreeNode nodeOpport      =   new RadTreeNode(str, CrmStr.opportunity);
                nodeOpport.Expanded         =   false;
                RadTree2.Nodes.Add(nodeOpport);
                loadOpportunities(contactId, nodeOpport);
            }
            if ( ShowQuotes )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_QUOTES", "Quotes");
                RadTreeNode nodeQuotes      =   new RadTreeNode(str, CrmStr.quote);
                RadTree2.Nodes.Add(nodeQuotes);
                nodeQuotes.Expanded         =   false;
                loadQuotes(contactId, nodeQuotes);
            }
            if ( ShowOrders )
            {
                string str              =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDERS", "Orders");
                RadTreeNode nodeOrders      =   new RadTreeNode(str, CrmStr.salesorder);
                nodeOrders.Expanded         =   false;
                RadTree2.Nodes.Add(nodeOrders);
                loadOrders(contactId, nodeOrders);
            }
            if ( ShowInvoices )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_INVOICES", "Invoices");
                RadTreeNode nodeInvoices    =   new RadTreeNode(str, CrmStr.invoice);
                nodeInvoices.Expanded       =   false;
                RadTree2.Nodes.Add(nodeInvoices);
                loadInvoices(contactId, nodeInvoices);
            }
            if ( ShowContracts )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACTS", "Contracts");
                RadTreeNode nodeOpport      =   new RadTreeNode(str, CrmStr.contract);
                nodeOpport.Expanded         =   false;
                RadTree2.Nodes.Add(nodeOpport);
                loadContracts(contactId, nodeOpport);
            }
            if ( ShowIncidents )
            {
                string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_INCIDENTS", "Incidents");
                RadTreeNode nodeIncidents   =   new RadTreeNode(str, CrmStr.incident);
                nodeIncidents.Expanded      =   false;
                RadTree2.Nodes.Add(nodeIncidents);
                loadIncidents(contactId, nodeIncidents);
            }
            
            RadTree2.DataBind(); // don't remove necessary for node template !!!
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ContactTree FillDetail END.",ContactTreeTrace.Sw.Info);
        }

        /// <summary>
        /// Load all contacts for selected contact
        /// </summary>
        protected void loadContacts(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadContacts BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.parentcustomerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                if ( ShowInactiveStatus )
                        filter.Conditions           =   new InternalConditionExpression[] { cond };
                else    filter.Conditions           =   new InternalConditionExpression[] { cond, CRMUtil.StateCodeIsActiveCondition };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.contact;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.contact);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;

                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                        ADNDynContact myContact                            =   new ADNDynContact();
                        myContact.InitTemplate(Wrapper,de,_columnDescriptors,null);
                        //myContact.EntityMData                              =   TConfig2.entityMetaData;
                        _columnDescriptors                          =   myContact.PropertyDescriptorCollection;
                        count++;
                    
                    string lastName                                 =   myContact.lastname; 
                    string firstName                                =   myContact.firstname; 
                    string nickname                                 =   myContact.nickname; 
                    string country                                  =   myContact.address1_country; 
                    string city                                     =   myContact.address1_city; 
                    string fonction                                 =   myContact.jobtitle; 
                    string zip                                      =   myContact.address1_postalcode; 
                    string name                                     =   myContact.lastname; 
                    string street                                   =   myContact.address1_line1; 
                    string tel1                                     =   myContact.telephone1; 
                    string email                                    =   myContact.emailaddress1; 
                    StringBuilder sb                                =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                 =   true;
                    AppendTxt(sb,lastName,firstName, ref begRow);
                    string str              =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_NICKNAME", "Nickname");
                    if ( !string.IsNullOrEmpty(nickname))
                    {
                        AppendTxt(sb,str,nickname, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_FONCTION", "Fonction");
                    if ( !string.IsNullOrEmpty(fonction))
                    {
                        AppendTxt(sb,str,fonction, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PHONE", "Phone 1");
                    if ( !string.IsNullOrEmpty(tel1))
                    {
                        AppendTxt(sb,str,tel1, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_EMAIL", "EMail");
                    if ( !string.IsNullOrEmpty(email))
                    {
                        AppendTxt(sb,str,string.Format("<a href='mailto:{0}'>{0}</a>",email), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ADDRESS1", "Street");
                    if ( !string.IsNullOrEmpty(street))
                    {
                        AppendTxt(sb,str,street, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CITY", "City");
                    if ( !string.IsNullOrEmpty(city))
                    {
                        AppendTxt(sb,str,city, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_POSTAL_CODE", "Zip");
                    if ( !string.IsNullOrEmpty(zip))
                    {
                        AppendTxt(sb,str,zip, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_COUNTRY", "Country");
                    if ( !string.IsNullOrEmpty(country))
                    {
                        AppendTxt(sb,str,country, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/conts/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myContact.contactid,myContact.fullname});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    RadTreeNode newNode         =   new RadTreeNode(myContact.fullname, myContact.contactid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myContact.contactid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadContacts ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        void AppendTxt(StringBuilder sb,string str1, string str2, ref bool begRow)
        {
            if ( begRow )
            {
                sb.Append("<tr>");
            }
            sb.AppendFormat("<td>{0} :</td><td> {1}</td>",str1,str2);
            if ( !begRow )
            {
                sb.Append("</tr>");
                begRow  =   true;
            }
            else begRow  =   false;
        }

        
        /// <summary>
        /// Load all relations for selected contact
        /// </summary>
        protected void loadRelations(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadRelations BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.customerrelationship;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.customerrelationship);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynCustomerRelationShip myCustomer       =   new ADNDynCustomerRelationShip();
                    myCustomer.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myCustomer.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myCustomer.PropertyDescriptorCollection;
                    count++;
                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                 =   true;
                    string str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PARTNER_NAME", "Partner");
                    if ( !string.IsNullOrEmpty(myCustomer.partneridName))
                    {
                        AppendTxt(sb,str,myCustomer.partneridName, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PARTNERROLE_DESCRIPTION", "Partner role");
                    if ( !string.IsNullOrEmpty(myCustomer.partnerroledescription))
                    {
                        AppendTxt(sb,str,myCustomer.partnerroledescription, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/accts/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myCustomer.partnerid,myCustomer.partneridName});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    RadTreeNode newNode         =   new RadTreeNode(myCustomer.partneridName, myCustomer.partnerid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myCustomer.partnerid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadRelations ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Load all incidents for selected contact
        /// </summary>
        protected void loadIncidents(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadIncidents BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.incident;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.incident);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynIncident myIncident                            =   new ADNDynIncident();
                    myIncident.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myIncident.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myIncident.PropertyDescriptorCollection;
                    count++;

                    string title                                =   myIncident.title; 
                    string createdate                           =   myIncident.createdonLocalDate.ToShortDateString(); 
                    string modifdate                            =   myIncident.modifiedonLocalDate.ToShortDateString(); 
                    string owner                                =   myIncident.ownerName;
                    string sujet                                =   myIncident.subjectName;
                    string ticketnumber                         =   myIncident.ticketnumber;
                    string stage                                =   myIncident.incidentstagecodeLabel;
                    string followupby                           =   myIncident.followupby;
                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                                 =   true;
                    string str                                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OWNER", "Owner");
                    if ( !string.IsNullOrEmpty(owner))
                    {
                        AppendTxt(sb,str,owner, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_SUBJECT", "Owner");
                    if ( !string.IsNullOrEmpty(sujet))
                    {
                        AppendTxt(sb,str,sujet, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_TICKET", "Ticket");
                    if ( !string.IsNullOrEmpty(ticketnumber))
                    {
                        AppendTxt(sb,str,ticketnumber, ref begRow);
                    }
                    str                             =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_CREATEDON", "Created on");
                    AppendTxt(sb,str,createdate, ref begRow);
                    str                             =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_MODIFIEDON", "Modified on");
                    AppendTxt(sb,str,modifdate, ref begRow);
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STAGE", "Stage");
                    if ( !string.IsNullOrEmpty(stage))
                    {
                        AppendTxt(sb,str,stage, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_FOLLOWUP_BY", "Followup by");
                    if ( !string.IsNullOrEmpty(followupby))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(followupby,true).ToShortDateString(), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}cs/cases/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myIncident.incidentid,title});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    str                         =    (string.IsNullOrEmpty(title)) ? ticketnumber:title;    
                    RadTreeNode newNode         =   new RadTreeNode(str, myIncident.incidentid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myIncident.incidentid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadIncidents ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Load all quotes for selected contact
        /// </summary>
        protected void loadQuotes(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadQuotes BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.quote;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.quote);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynQuote myQuote                            =   new ADNDynQuote();
                    myQuote.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myQuote.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myQuote.PropertyDescriptorCollection;
                    count++;

                    string number                               =   myQuote.quotenumber;
                    string name                                 =   myQuote.name;
                    string tarif                                =   myQuote.pricingerrorcodeLabel; 
                    string amount                               =   myQuote.totalamount.ToString(); 
                    string currency                             =   myQuote.transactioncurrencyName;
                    string status                               =   myQuote.statuscodeName; 
                    string createdate                           =   myQuote.createdonLocalDate.ToShortDateString(); 
                                        
                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                                 =   true;
                    string str                                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_QUOTENUMBER", "Quote number");
                    if ( !string.IsNullOrEmpty(number))
                    {
                        AppendTxt(sb,str,number, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_CREATEDON", "Created on");
                    AppendTxt(sb,str,createdate, ref begRow);
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PRICING", "Pricing");
                    if ( !string.IsNullOrEmpty(tarif))
                    {
                        AppendTxt(sb,str,tarif, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_AMOUNT", "Amount");
                    if ( !string.IsNullOrEmpty(amount))
                    {
                        AppendTxt(sb,str,amount+"&nbsp;"+currency, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATUS", "Status");
                    if ( !string.IsNullOrEmpty(status))
                    {
                        AppendTxt(sb,str,status, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/quotes/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myQuote.quoteid,name});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");
                    str                         =    (string.IsNullOrEmpty(name)) ? number:name;    
                    RadTreeNode newNode         =   new RadTreeNode(str, myQuote.quoteid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myQuote.quoteid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadQuotes ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }


        /// <summary>
        /// Load all invoices for selected contact
        /// </summary>
        protected void loadInvoices(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadInvoices BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.invoice;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.invoice);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynInvoice myInvoice                            =   new ADNDynInvoice();
                    myInvoice.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myInvoice.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myInvoice.PropertyDescriptorCollection;
                    count++;

                    string id                                   =   myInvoice.invoicenumber; 
                    string name                                 =   myInvoice.name; 
                    string createdate                           =   myInvoice.createdonLocalDate.ToShortDateString(); 
                    string tarif                                =   myInvoice.pricelevelName;
                    string amount                               =   myInvoice.totalamount.ToString();
                    string currency                             =   myInvoice.transactioncurrencyName;
                    string status                               =   myInvoice.statuscodeName; 
                    
                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                                 =   true;
                    string str                                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_INVOICE_NUMBER", "Invoice number");
                    if ( !string.IsNullOrEmpty(id))
                    {
                        AppendTxt(sb,str,id, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_CREATEDON", "Created on");
                    AppendTxt(sb,str,createdate, ref begRow);
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PRICING", "Pricing");
                    if ( !string.IsNullOrEmpty(tarif))
                    {
                        AppendTxt(sb,str,tarif, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_AMOUNT", "Amount");
                    if ( !string.IsNullOrEmpty(amount))
                    {
                        AppendTxt(sb,str,amount+"&nbsp;"+currency, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATUS", "Status");
                    if ( !string.IsNullOrEmpty(status))
                    {
                        AppendTxt(sb,str,status, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/invoice/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myInvoice.invoiceid,name});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    str                         =    (string.IsNullOrEmpty(name)) ? id:name;    
                    RadTreeNode newNode         =   new RadTreeNode(str, myInvoice.invoiceid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myInvoice.invoiceid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadInvoices ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Load all orders for selected contact
        /// </summary>
        protected void loadOrders(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadOrders BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.salesorder;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.salesorder);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynSalesOrder myOrder                    =   new ADNDynSalesOrder();
                    myOrder.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myOrder.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myOrder.PropertyDescriptorCollection;
                    count++;

                    string id                                   =   myOrder.ordernumber; 
                    string name                                 =   myOrder.name; 
                    string createdate                           =   myOrder.createdonLocalDate.ToShortDateString(); 
                    string tarif                                =   myOrder.pricelevelName; 
                    string amount                               =   myOrder.totalamount.ToString();
                    string currency                             =   myOrder.transactioncurrencyName;
                    string datefulfilled                        =   myOrder.datefulfilled; 
                    string submitdate                           =   myOrder.submitdate; 
                    string status                               =   myOrder.statuscodeName; 
                        

                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                                 =   true;
                    string str                                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_NUMBER", "Order number");
                    if ( !string.IsNullOrEmpty(id))
                    {
                        AppendTxt(sb,str,id, ref begRow);
                    }
                    str                             =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ORDER_CREATEDON", "Created on");
                    AppendTxt(sb,str,createdate, ref begRow);
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_PRICING", "Pricing");
                    if ( !string.IsNullOrEmpty(tarif))
                    {
                        AppendTxt(sb,str,tarif, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_AMOUNT", "Amount");
                    if ( !string.IsNullOrEmpty(amount))
                    {
                        AppendTxt(sb,str,amount+"&nbsp;"+currency, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_DATE_SUBMITTED", "Amount");
                    if ( !string.IsNullOrEmpty(submitdate))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(submitdate,true).ToShortDateString(), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_DATE_FULLFILLED", "Amount");
                    if ( !string.IsNullOrEmpty(datefulfilled))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(datefulfilled,true).ToShortDateString(), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATUS", "Status");
                    if ( !string.IsNullOrEmpty(status))
                    {
                        AppendTxt(sb,str,status, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/salesorder/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myOrder.salesorderid,name});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    str                         =    (string.IsNullOrEmpty(name)) ? id:name;    
                    RadTreeNode newNode         =   new RadTreeNode(str, myOrder.salesorderid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myOrder.salesorderid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadOrders ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Load all Contracts for selected contact
        /// </summary>
        protected void loadContracts(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadContracts BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.contract;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.contract);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynContract myContract                       =   new ADNDynContract();
                    myContract.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myContract.EntityMData                        =   TConfig2.entityMetaData;
                    _columnDescriptors                              =   myContract.PropertyDescriptorCollection;
                    count++;

                    string title                                    =   myContract.title; 
                    string number                                   =   myContract.contractnumber; 
                    string contractservicelevelcodeName             =   myContract.contractservicelevelcodeLabel; 
                    string allotmenttype                            =   myContract.allotmenttypecodeLabel;
                    string status                                   =   myContract.statuscodeName; 
                    string totalprice                               =   myContract.totalprice.ToString(); 
                    string currency                                 =   myContract.transactioncurrencyName;
                    string activeOn                                 =   myContract.activeon;
                    string expireson                                =   myContract.expireson;
                    string cancelon                                 =   myContract.cancelon;
                    string billingstarton                           =   myContract.billingstarton;
                    string billingendon                             =   myContract.billingendon;
                    string billingfrequencycodeName                 =   myContract.billingfrequencycodeLabel;
                    
                    StringBuilder sb            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                 =   true;
                    string str                  =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_NUMBER", "Contract number");
                    if ( !string.IsNullOrEmpty(number))
                    {
                        AppendTxt(sb,str,number, ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_ALLOTMENT", "Allotment type");
                    if ( !string.IsNullOrEmpty(allotmenttype))
                    {
                        AppendTxt(sb,str,allotmenttype, ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_SERVICELEVEL", "Service level");
                    if ( !string.IsNullOrEmpty(contractservicelevelcodeName))
                    {
                        AppendTxt(sb,str,contractservicelevelcodeName, ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_TOTALPRICE", "Estimated value");
                    if ( !string.IsNullOrEmpty(totalprice))
                    {
                        AppendTxt(sb,str,totalprice+"&nbsp;"+currency, ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_ACTIVEON", "Active on");
                    if ( !string.IsNullOrEmpty(activeOn))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(activeOn,true).ToShortDateString(), ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_EXPIRESON", "Expires on");
                    if ( !string.IsNullOrEmpty(expireson))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(expireson,true).ToShortDateString(), ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_CANCELON", "Cancel on");
                    if ( !string.IsNullOrEmpty(cancelon))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(cancelon,true).ToShortDateString(), ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_BILLINGSTARTON", "Billing start on");
                    if ( !string.IsNullOrEmpty(billingstarton))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(billingstarton,true).ToShortDateString(), ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_BILLINGENDON", "Billing end on");
                    if ( !string.IsNullOrEmpty(billingendon))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(billingendon,true).ToShortDateString(), ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CONTRACT_BILLING_FREQUENCY", "Billing frequency");
                    if ( !string.IsNullOrEmpty(billingfrequencycodeName))
                    {
                        AppendTxt(sb,str,billingfrequencycodeName, ref begRow);
                    }
                    
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATUS", "Status");
                    if ( !string.IsNullOrEmpty(status))
                    {
                        AppendTxt(sb,str,status, ref begRow);
                    }
                    str                         =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}cs/contracts/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myContract.contractid,title});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    str                         =    (string.IsNullOrEmpty(title)) ? number:title;    
                    RadTreeNode newNode         =   new RadTreeNode(str, myContract.contractid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myContract.contractid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadContracts ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Load all opportunities for selected contact
        /// </summary>
        protected void loadOpportunities(Guid contactId, RadTreeNode parentNode)
        {
            if ( ContactTreeTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree loadOpportunities BEG contactId: {0}", contactId),ContactTreeTrace.Sw.Info);
            try
            {
                InternalConditionExpression cond    =   new InternalConditionExpression();
                cond.AttributeName                  =   CrmStr.customerid;
                cond.Operator                       =   InternalConditionOperator.Like;
                cond.Values                         =   new object[] { contactId };

                InternalFilterExpression filter     =   new InternalFilterExpression();

                filter.FilterOperator               =   InternalLogicalOperator.And;
                filter.Conditions                   =   new InternalConditionExpression[] { cond };

                InternalQueryExpression query       =   new InternalQueryExpression();
                query.Criteria                      =   filter;
                query.EntityName                    =   CrmStr.opportunity;
                query.ColumnSet                     =   new InternalAllColumns();

                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,CrmStr.opportunity);
                InternalBusinessEntityCollection allEnt             =   allEntQuery.Retrieve(query);
                PropertyDescriptorCollection _columnDescriptors     =   null;
                int count                                           =   0;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                    ADNDynOpportunity myOpport                  =   new ADNDynOpportunity();
                    myOpport.InitTemplate(Wrapper,de,_columnDescriptors,null);
                    //myOpport.EntityMData                              =   TConfig2.entityMetaData;
                    _columnDescriptors                          =   myOpport.PropertyDescriptorCollection;
                    count++;

                    string name                                 =   myOpport.name; 
                    string status                               =   myOpport.statuscodeName; 
                    string closeprobability                     =   myOpport.closeprobability.ToString(); 
                    string estimatedclosedate                   =   myOpport.estimatedclosedate;
                    string actualclosedate                      =   myOpport.actualclosedate;
                    string actualvalue                          =   myOpport.actualvalue.ToString();
                    string revenu                               =   myOpport.estimatedvalue.ToString();
                    string currency                             =   myOpport.transactioncurrencyName;
                    string step                                 =   myOpport.salesstagecodeLabel;
                    
                    StringBuilder sb                            =   new StringBuilder();
                    sb.Append("<table class='contacttreetable' cellspacing='2px' cellpadding='2px'>");
                    bool begRow                 =   true;
                    string str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STEP", "Step");
                    if ( !string.IsNullOrEmpty(step))
                    {
                        AppendTxt(sb,str,step, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_CLOSE_PROBA", "Close probability");
                    if ( !string.IsNullOrEmpty(closeprobability))
                    {
                        AppendTxt(sb,str,closeprobability, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ESTIMATED_CLOSE_DATE", "Estimated close date");
                    if ( !string.IsNullOrEmpty(estimatedclosedate))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(estimatedclosedate,true).ToShortDateString(), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ESTIMATED_VALUE", "Estimated value");
                    if ( !string.IsNullOrEmpty(revenu))
                    {
                        AppendTxt(sb,str,revenu+"&nbsp;"+currency, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACTUAL_CLOSE_DATE", "Actual close date");
                    if ( !string.IsNullOrEmpty(actualclosedate))
                    {
                        AppendTxt(sb,str,CRMUtil.ConvertDateFromCrm(actualclosedate,true).ToShortDateString(), ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_ACTUAL_VALUE", "Estimated value");
                    if ( !string.IsNullOrEmpty(actualvalue))
                    {
                        AppendTxt(sb,str,actualvalue+"&nbsp;"+currency, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_STATUS", "Status");
                    if ( !string.IsNullOrEmpty(status))
                    {
                        AppendTxt(sb,str,status, ref begRow);
                    }
                    str                     =   LocalizeHelper.Localize("CRM_ACCOUNTTREE_OPEN_IN_CRM", "Open in Crm");
                    if ( ShowOpenInCrmLink )
                    {
                        if ( begRow )
                        {
                            sb.Append("<tr>");
                        }
                        sb.AppendFormat("<td>{0} :</td><td><a href='{1}sfa/opps/edit.aspx?id={2}' target='_blank'>{3}</a></td>",
                            new object[]{str,CrmServerUrl,myOpport.opportunityid,name});
                        if ( !begRow )
                        {
                            sb.Append("</tr>");
                            begRow  =   true;
                        }
                        else begRow  =   false;
                    }
                    if ( begRow )
                    {
                        sb.Append("<td></td></tr>");
                    }
                    sb.Append("</table>");

                    RadTreeNode newNode         =   new RadTreeNode(name, myOpport.opportunityid.ToString());
                    newNode.Expanded            =   false;
                    parentNode.Nodes.Add(newNode);
                    RadTreeNode detNode         =   new RadTreeNode(sb.ToString(), myOpport.opportunityid.ToString());
                    detNode.Expanded            =   false;
                    newNode.Nodes.Add(detNode);
                    return true; //continue
                });
                parentNode.Text                 =   string.Format("{0} ({1})",parentNode.Text,count);
            }
            catch(Exception ex)
            { 
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree loadOpportunities ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }
        
        void GridDock_Command(object sender, DockCommandEventArgs e)
        {
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree GridDock_Command name: {0}.", e.Command.Name),ContactTreeTrace.Sw.Info);
            RadTreeNode nd = RadTree1.SelectedNode;
            if ( nd == null )
                return;
            switch (e.Command.Name)
            {
                case "DeleteBtn":
					CloseContact(nd);   
                    break;
            }
        }

        /// <summary>
        /// Close selected contact
        /// </summary>
		void CloseContact(RadTreeNode sourceNode)
		{
			try
			{
				if (ContactTreeTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree CloseContact for contact:'{0}'.",sourceNode.Text),ContactTreeTrace.Sw.Info);
				Guid contactId		        =   new Guid(sourceNode.Value);
                // under crm do not close current contact
                if ( IsUnderCRM && ( EntityID == contactId ) )
                    return;
                ADNDynContact mycontact     =   new ADNDynContact(Wrapper,contactId);
                mycontact.Retrieve();
                Wrapper.Util.SetStateOperation(CrmStr.contact, contactId, CrmStr.StateInactive,-1);
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree CloseContact ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
		}

        #region Nodes operations for RadTree1

        /// <summary>
		/// Handler for a right button menu click in treeView
		/// </summary>
        void RadTree1_ContextMenuItemClick(object o, RadTreeViewContextMenuEventArgs e)
        {
			string contextCommand = e.MenuItem.Value;
			
			RadTreeNode currentNode = e.Node;

			switch (contextCommand)
			{
				case "CloseContact":          
					CloseContact( currentNode);   
					break;
				case "AddContact":
					break;
			}
		}
        
        /// <summary>
		/// User has edited a contact name, we change it
		/// </summary>
        void RadTree1_NodeEdit(object o, RadTreeNodeEditEventArgs e)
        {
			RadTreeNode sourceNode  =   e.Node;
			string ntext            =   e.Text.Trim();

            Guid contactId                  =   new Guid(e.Node.Value);
            ADNDynContact mycontact         =   new ADNDynContact(Wrapper,contactId);
            mycontact.Retrieve();
            if ( mycontact.name == ntext )
                return;
            if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeEdit  {0}-{1} changed to {2}", sourceNode.Text, sourceNode.Value, ntext),ContactTreeTrace.Sw.Info);
			try
			{
                string[] rst            =   ntext.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
                if (rst.Length > 1)
                {
                    mycontact.firstname = rst[0].Trim();
                    mycontact.lastname = rst[1].Trim();
                }
                else  mycontact.lastname = ntext;
                mycontact.Update();
                mycontact.Retrieve();
				sourceNode.Text         = mycontact.fullname;
                // refresh the radgrid
                SelectNode(sourceNode);
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree RadTree1_NodeEdit ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
			}
		}

        /// <summary>
        /// User has changed the parent contact 
        /// </summary>
		void ChangeParentcontact(RadTreeNode sourceNode, RadTreeNode destNode)
		{
			try
			{
				if (ContactTreeTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree ChangeParentcontact for contact:'{0}' new parent: '{1}'",sourceNode.Text,destNode.Text),ContactTreeTrace.Sw.Info);
				Guid contactId		            =   new Guid(sourceNode.Value);
                ADNDynContact mycontact         =   new ADNDynContact(Wrapper,contactId);
                mycontact.Retrieve();
                mycontact.parentcustomerid      =   new Guid(destNode.Value);
                mycontact.Update();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree ChangeParentcontact ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
				throw;
			}
		}

        /// <summary>
		/// User has moved a node
		/// </summary>
        void RadTree1_NodeDrop(object o, RadTreeNodeDragDropEventArgs e)
        {
            // Fetch event data 
            RadTreeNode sourceNode		= e.SourceDragNode;
            RadTreeNode destNode		= e.DestDragNode;
			if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeDrop  {0}.",sourceNode.Text),ContactTreeTrace.Sw.Info);
    
            // node may have been dropped outside treeviews, or on itself
			// We don't accept inversing hierarchy
			if (destNode == null || sourceNode.Equals(destNode) || sourceNode.IsAncestorOf(destNode) )
				return;

			RadTreeViewDropPosition d	=	e.DropPosition;

			if (ContactTreeTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeDrop  {0} -{1}- {2}",sourceNode.Text,d,destNode.Text),ContactTreeTrace.Sw.Info);
			try
			{
				bool changeParent       =   (destNode.ParentNode != sourceNode.ParentNode );
				switch (d)
				{
					case RadTreeViewDropPosition.Above:
						sourceNode.Owner.Nodes.Remove(sourceNode);
						destNode.InsertBefore(sourceNode);
						if (ContactTreeTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeDrop: {0} changeParent: {1}", sourceNode.Text, changeParent),ContactTreeTrace.Sw.Info);
						if (changeParent)
							ChangeParentcontact(sourceNode, destNode.ParentNode);
						break;
					case RadTreeViewDropPosition.Below:
						sourceNode.Owner.Nodes.Remove(sourceNode);
						destNode.InsertAfter(sourceNode);
						if (ContactTreeTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeDrop: {0} changeParent: {1}", sourceNode.Text, changeParent),ContactTreeTrace.Sw.Info);
						if (changeParent)
							ChangeParentcontact(sourceNode, destNode.ParentNode);
						break;
					case RadTreeViewDropPosition.Over:
                        // difference in rules here
				        if (destNode.ParentNode == sourceNode.ParentNode )
                            changeParent       =   true;
				        else if (destNode == sourceNode.ParentNode )
                            changeParent       =   false;
						if (ContactTreeTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree RadTree1_NodeDrop: {0} changeParent: {1}", sourceNode.Text, changeParent),ContactTreeTrace.Sw.Info);
						sourceNode.Owner.Nodes.Remove(sourceNode);
						destNode.Nodes.Add(sourceNode);
						if (changeParent)
							ChangeParentcontact(sourceNode, destNode);
						break;
					default:
						return;
				}
				// Expand destination node to see result of swap immediately.
				destNode.ExpandChildNodes();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ContactTree RadTree1_NodeDrop ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
			}
        }

        #endregion


        #region Detail Tree Template

        class TextBoxTemplate : ITemplate
        {
           public void InstantiateIn(Control container)
           {
                if (ContactTreeTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree InstantiateIn container: {0}.", container),ContactTreeTrace.Sw.Info);
               Literal label1       =   new Literal();
               label1.ID            =   "ItemLiteral";
               //label1.Text          =   "Text";
               label1.DataBinding   +=  new EventHandler(label1_DataBinding);
               container.Controls.Add(label1);
           }

           private void label1_DataBinding(object sender, EventArgs e)
           {
               Literal target       =   (Literal)sender;
               RadTreeNode node     =   (RadTreeNode)target.BindingContainer;
               string nodeText      =   (string)DataBinder.Eval(node, "Text");
               target.Text          =   nodeText;
                if (ContactTreeTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ContactTree label1_DataBinding nodeText: {0}.", nodeText),ContactTreeTrace.Sw.Info);
           }
        }

        #endregion Detail Tree Template

        #region Dock management

        const string pgCookieName   =   "AddonNice_contactTree";
        
        protected override string DockWindowCookieName
        {
            get
            {
                return pgCookieName;
            }
        }

        protected override RadDockLayout DockWindowLayout
        {
            get
            {
                return RadDockLayout1;
            }
        }
        #endregion Dock management

        #region Std Control override

        public override void Page_PreInit(object sender, EventArgs e)
        {
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree Page_PreInit BEG.",ModuleTraceSwitch.Sw.Info);
           base.Page_PreInit(sender, e);
            //string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            //updateBtn.SkinID    =   "Update_" + strcult;
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree Page_PreInit END.",ModuleTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
        {
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree OnInit BEG.",ModuleTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmContactTree OnInit END.",ModuleTraceSwitch.Sw.Info);
        }
        
        private void InitializeComponent()
        {
            Load                            +=  new EventHandler(Page_Load);
            RadTree1.NodeDrop               +=  new RadTreeViewDragDropEventHandler(RadTree1_NodeDrop);
            RadTree1.NodeEdit               +=  new RadTreeViewEditEventHandler(RadTree1_NodeEdit);
			RadTree1.NodeClick		        +=  new RadTreeViewEventHandler(RadTree1_NodeClick);
            RadTree1.ContextMenuItemClick   +=  new RadTreeViewContextMenuEventHandler(RadTree1_ContextMenuItemClick);
            GridDock.Command                +=  new DockCommandEventHandler(GridDock_Command);
            RadDockLayout1.LoadDockLayout   +=  new DockLayoutEventHandler(DockWindowLayout_LoadDockLayout);
            RadDockLayout1.SaveDockLayout   +=  new DockLayoutEventHandler(DockWindowLayout_SaveDockLayout);
            RadTree2.NodeTemplate           =   new TextBoxTemplate();
          }
      
        #endregion Std Control override

     }
}